const TXuuid = '86530022-43E6-47B7-9CB0-5FC21D4AE340'
const RXuuid = '86530033-43E6-47B7-9CB0-5FC21D4AE340'
//搜蓝牙设备
export async function searchBLEDevice(callback){
  let deviceList = []
  try{
    await uni.openBluetoothAdapter()
  } catch(err){
    console.log(err)
    return uni.navigateBack({
      success(){
         uni.showToast({
          title: '蓝牙或定位未打开', 
          icon:'none'
        })
      }
    })
    
  }
  console.log('打开蓝牙扫描')
  uni.startBluetoothDevicesDiscovery({
    allowDuplicatesKey: false,
    services:["0000FEFF-0000-1000-8000-00805F9B34FB"]
  })
  // 监听扫描到新设备事件
  uni.onBluetoothDeviceFound((res) => {
    //console.log('搜索中')
    res.devices.forEach((device) => {
      // 这里可以做一些过滤
      if (device.name == 'J-KEY') {
        deviceList.push(device)
        console.log('找到姐钥设备')
        callback(device.deviceId)
      }
    })
  })
}
//初始化蓝设备
export function initBLE(){
  uni.openBluetoothAdapter({
    success(res){
      console.log(res)
    },
    fail(err){
      console.log(err)
    }
  })
}
//判断蓝牙是否可用
export function canUseBLE(){}

//连接设备
export function connectBLE(deviceId,callback){
  console.log(deviceId)
  uni.createBLEConnection({
    deviceId, // 搜索到设备的 deviceId
    success: () => {
      // 连接成功，获取服务
      console.log('连接成功，获取服务')
	  setTimeout(()=>{
		  uni.getBLEDeviceServices({
		    deviceId, // 搜索到设备的 deviceId
		    success: (res) => {
		      console.log('连接成功',res,deviceId)
		      let result;
		      res.services.forEach(x => {
		  			  console.log('service',x)
		        if (x.uuid.indexOf('0011') !== -1) {
		          result = x.uuid
		        }
		      })
		      if(result){
		        //如果连接成功，存入手机内存中
		        let historyDeviceList =  uni.getStorageSync('historyDeviceList') || []
		        console.log(historyDeviceList)
		        if(!historyDeviceList.some(x=>{
		          return x.deviceId == deviceId
		        })){
		          historyDeviceList.push({
		            deviceId
		          })
		          uni.setStorageSync('historyDeviceList',historyDeviceList)
		        }
		      }
		      callback(result)
		    },
		    fail: (err) => {
		      console.log(err)
		      uni.showToast({
		        title: '连接失败',
		        icon: 'error'
		      })
		    }
		  })
	  },1200)
      
    },
    fail: () => {
      uni.hideLoading()
      uni.showToast({
        title: '连接失败',
        icon: 'error'
      })
    }
  })

}

//断开设备连接
export function closeBLE(){}

//监听蓝牙返回值
export function monitorBLE(callback){
    let BLEInfo = getApp().globalData.BLEInfo
    let deviceId = BLEInfo.deviceId
    let serviceId = BLEInfo.serviceId
    let characteristicId = TXuuid
    uni.getBLEDeviceCharacteristics({
      deviceId, // 搜索到设备的 deviceId
      serviceId, // 上一步中找到的某个服务
      success: (res) => {
        console.log(res)
      }
    })
    uni.notifyBLECharacteristicValueChange({
      state: true, // 启用 notify 功能
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
      deviceId,
      // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
      serviceId,
      // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
      characteristicId,
      success(res) {
        console.log('notifyBLECharacteristicValueChange success', res.errMsg)
      }
    })
    // 操作之前先监听，保证第一时间获取数据
    uni.onBLECharacteristicValueChange((result) => {

      let res = hexToStr(result.value)
      // 读取电量
      if (res.slice(2, 4) === '01') {
        
       let batteryNumber = parseInt('0x' + res.slice(8, 10))
       console.log('获取电量成功',batteryNumber)
       getApp().globalData.BLEInfo.batteryValue = batteryNumber
       callback(batteryNumber)
      }
      if (res.slice(2, 4) === '03') {
        console.log('马上进行关机')
        uni.hideLoading({
          success: (res) => {

          },
        })
        uni.closeBLEConnection({
          deviceId:deviceId
        })
        uni.closeBluetoothAdapter({})
      }
    })
}
export async function delDevice(){
  let BLEInfo = getApp().globalData.BLEInfo
  let deviceId = BLEInfo.deviceId
  uni.showLoading({
    title:'处理中'
  })
  await sleep(500)
  uni.closeBLEConnection({
    deviceId:deviceId
  })
  uni.closeBluetoothAdapter({})
  uni.hideLoading()
}

//字符串转16进制
export function strToHex(str){
  //str = '7301aa01001e6f'
  let typedArray = new Uint8Array(str.match(/[\da-f]{2}/gi).map(function (h) {
    return parseInt(h, 16)
  }))

  let buffer = typedArray.buffer
  return buffer
}

//16进制转字符串
export function hexToStr(buffer){
  let hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}

////模拟sleep
export function sleep(time=1000){
  return new Promise((resolve,reject)=>{
    setTimeout(resolve,time)
  })
}

// 查询电量
export function queryBattery(){
    let buffer = strToHex('7301aa01001e6f')
    let BLEInfo = getApp().globalData.BLEInfo
    console.log(BLEInfo)
    let deviceId = BLEInfo.deviceId
    let serviceId = BLEInfo.serviceId
    let characteristicId = RXuuid

    uni.writeBLECharacteristicValue({
      // 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
      deviceId,
      // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
      serviceId,
      // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
      characteristicId,
      // 这里的value是ArrayBuffer类型
      value: buffer,
      success(res) {
        console.log('writeBLECharacteristicValue success', res)
      }
    })
}

// 电机出水
export async function devicePump(time, sleepTime){
  time = time.toString(16)
  time.length == 1 ? time = '0' + time : ''
  let a = '7300aa030100' + time + '496f'
  let buffer = strToHex(a)
  let BLEInfo = getApp().globalData.BLEInfo
  let deviceId = BLEInfo.deviceId
  let serviceId = BLEInfo.serviceId
  let characteristicId = RXuuid
	
	console.log(time,BLEInfo)
  uni.writeBLECharacteristicValue({
    // 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
    deviceId,
    // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
    serviceId,
    // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
    characteristicId,
    // 这里的value是ArrayBuffer类型
    value: buffer,
    success(res) {
      console.log('抽水 success', res)
    }
  })
  await sleep(sleepTime)
}

//关机
export async function powerOff(){
    let a = '7303aa0100216f'
    let buffer = strToHex(a)
    let BLEInfo = getApp().globalData.BLEInfo
    let deviceId = BLEInfo.deviceId
    let serviceId = BLEInfo.serviceId
    let characteristicId = RXuuid
    uni.showLoading({
      title: '处理中',
    })
    await sleep(500)
    uni.writeBLECharacteristicValue({
      // 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
      deviceId,
      // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
      serviceId,
      // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
      characteristicId,
      // 这里的value是ArrayBuffer类型
      value: buffer,
      success(res) {
        console.log('关机 success', res)
      }
    })
}
// 出水暂停
export async function stopPump(){
    getApp().globalData.endMode = true
    let a = '7302aa0100206f'
    let buffer = strToHex(a)
    let BLEInfo = getApp().globalData.BLEInfo
    let deviceId = BLEInfo.deviceId
    let serviceId = BLEInfo.serviceId
    let characteristicId = RXuuid
    await sleep(220)
    uni.writeBLECharacteristicValue({
      // 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
      deviceId,
      // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
      serviceId,
      // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
      characteristicId,
      // 这里的value是ArrayBuffer类型
      value: buffer,
      success(res) {
        console.log('停止 success', res)
      }
    })
}

// 电机调速
export async function changeDevicePower(power){
  power = '0' + power.toString(16)
    let a = '7304aa01' + power + '246f'
    let buffer = strToHex(a)
    let BLEInfo = getApp().globalData.BLEInfo
    let deviceId = BLEInfo.deviceId
    let serviceId = BLEInfo.serviceId
    let characteristicId = RXuuid

    uni.writeBLECharacteristicValue({
      // 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
      deviceId,
      // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
      serviceId,
      // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
      characteristicId,
      // 这里的value是ArrayBuffer类型
      value: buffer,
      success(res) {
        console.log('调速 success', res)
      }
    })
    await sleep(250)
}

//// 模式开始
export async function runMode(config){
  getApp().globalData.endMode = false
  for (let i of config.items) {

    let start = new Date()
    await changeDevicePower(i.strength)
    if(getApp().globalData.endMode){
      return
    }
    await devicePump(i.choushui_sec * 10, (i.sleep_sec + i.choushui_sec) * 1000)
    let end = new Date()
    console.log('结束执行', i)
    console.log('time is', end - start)
  }
}